/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.feature.mail.core.util;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.StringWriter;
import java.util.Map;
import java.util.Properties;

/**
 * velocity模板工具类
 *
 * @author yoara
 */
public class VelocityUtil {
	private static final Logger log = LoggerFactory.getLogger(VelocityUtil.class);

	//-------------------------将邮件的volocity抽取出来------------------------------------
	//-------------------------------start---------------------------------------------

	private static VelocityEngine engine;

	static{
		engine = new VelocityEngine();

		//初始化参数
		Properties properties=new Properties();
		//设置velocity资源加载方式为class
		properties.setProperty("resource.loader", "class");
		//设置velocity资源加载方式为file时的处理类
		properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");

		try {
			engine.init(properties);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
	}

	/**
	 * 渲染指定的模板文件
	 * @param fileUrl 文件的url
	 * @param model	  数据模型
	 * @return	渲染后的数据
	 */
	public static String templateMerge(String fileUrl, Map<String, Object> model){

		Template template;
		StringWriter writer = new StringWriter();
		try {
			template = engine.getTemplate(fileUrl, "UTF-8");

			template.merge(convertVelocityContext(model), writer);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return writer.toString();
	}

	//-------------------------------end---------------------------------------------


	public static String evaluate(Map<String, Object> model, String strTemplate){
		//输出流
		StringWriter writer = new StringWriter();
		//渲染模板
		try {
			Velocity.evaluate(convertVelocityContext(model), writer, "", strTemplate);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return writer.toString();
	}


	/**
	 * 把Map转换成Context
	 */
	@SuppressWarnings("unused")
	private static VelocityContext convertVelocityContext(Map<String, Object> map) {
		VelocityContext context = new VelocityContext();
		if (map == null) {
			return context;
		}
		for (Map.Entry<String, Object> entry : map.entrySet()) {
			context.put(entry.getKey(), entry.getValue());
		}
		return context;
	}
}
